package com.haven.webrobotserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haven.webrobotserver.domain.TestdataItem;
import com.haven.webrobotserver.service.TestdataItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin("http://localhost:8080")
@RequestMapping("/testdataItem")
public class TestdataItemController {

    @Autowired
    private TestdataItemService testdataItemService;

    @GetMapping("/getTestdataItemListByTestdataId")
    public JSONObject getTestdataItemListByTestdataId(@RequestParam(name = "testdataId") int tesetdataId){
        JSONObject result = new JSONObject();

        try{
            List<TestdataItem> list = testdataItemService.getTestdataItemListByTest(tesetdataId);
            if(list != null){
                String s = JSON.toJSONString(list);
                JSONArray objects = JSON.parseArray(s);
                result.put("data",objects);
                result.put("status",200);
                result.put("msg","success");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","fail");
        }

        return result;
    }

    @PostMapping("/updateTestdataItem")
    public JSONObject updateTestdataItem(@RequestBody TestdataItem testdataItem){
        JSONObject result = new JSONObject();

        try{
            testdataItemService.updateTestdataItem(testdataItem);
            result.put("status",200);
            result.put("msg","success");
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","fail");
        }

        return result;
    }

    @PostMapping("/newTestdataItem")
    public JSONObject newTestdataItem(@RequestBody TestdataItem testdataItem){
        JSONObject result = new JSONObject();

        try{
            testdataItemService.newTestdataItem(testdataItem);
            result.put("status",200);
            result.put("data",testdataItem);
            result.put("msg","success");
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","fail");
        }

        return result;
    }

    @GetMapping("/deleteOne")
    public JSONObject deleteOne(@RequestParam(name="id") int id){
        JSONObject result = new JSONObject();

        try{
            testdataItemService.deleteOne(id);
            result.put("status",200);
            result.put("msg","success");
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","fail");
        }

        return result;
    }

}
